const { AlipaySdk } = require("alipay-sdk");
const fs = require("fs");
const path = require("path");
const router = require("koa-router")();
const { key } = require("../config/default");
const jwt = require("koa-jwt")({ secret: key });
// 实例化客户端
const alipaySdk = new AlipaySdk({
  // 设置应用 ID
  appId: "9021000133628166",
  // 设置应用私钥
  privateKey: fs.readFileSync(
    path.resolve(__dirname, "../key/private-key.pem"),
    "ascii"
  ),
  // 设置支付宝公钥
  alipayPublicKey: fs.readFileSync(
    path.resolve(__dirname, "../key/alipay-public-key.pem"),
    "ascii"
  ),
  // 密钥类型，请与生成的密钥格式保持一致，参考平台配置一节
  // keyType: 'PKCS1',
  // 设置网关地址，默认是 https://openapi.alipay.com
  // endpoint: "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
  gateway: "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
});

router.get("/pay", async (ctx) => {
  ctx.verifyParams({
    title: { type: "string", required: true },
    id: { type: "string", required: true },
    price: { type: "string", required: true },
  });

  
  const { title, id, price } = ctx.request.query;

  const bizContent = {
    out_trade_no: id,
    total_amount: price,
    subject: title,
    product_code: "QUICK_WAP_WAY",
  };
  try {
    const url = await alipaySdk.pageExecute("alipay.trade.wap.pay", "GET", {
      bizContent,
      returnUrl: "http://localhost:5173/success",
    });
    ctx.body = {
      code: 200,
      message: "支付链接生成",
      data: url,
    };
  } catch (error) {
    ctx.body = {
      code: 200,
      message: "支付失败",
      error: error,
    };
  }
});

router.get("/query", async (ctx) => {
  const { id } = ctx.request.query;

  try {
    const resp = await alipaySdk.exec("alipay.trade.query", {
      bizContent: {
        out_trade_no: id,
      },
    });
    const { code, tradeStatus } = resp;
    if (code === "10000") {
      let message = "";
      switch (tradeStatus) {
        case "WAIT_BUYER_PAY":
          message = "等待买家付款";
          ctx.body = {
            code: 201,
            message,
          };
          return;
        case "TRADE_CLOSED":
          message = "未付款交易超时关闭，或支付完成后全额退款";
          ctx.body = {
            code: 202,
            message,
          };
          return;
        case "TRADE_SUCCESS":
          message = "交易支付成功";
          break;
        case "TRADE_FINISHED":
          message = "交易结束，不可退款";
          break;
      }
      ctx.body = {
        code: 200,
        message,
      };
    } else {
      ctx.body = {
        code: 404,
        message: "当前订单还未查询到",
      };
    }
  } catch (error) {
    console.log(error);
    ctx.body = {
      code: 400,
      message: "查询失败",
      error,
    };
  }
});

module.exports = router;
